const router = require('koa-router')()

router.get('/', async (ctx, next) => {
  ctx.cookies.set("username", "huangzelin")
  await ctx.render('index', {
    title: 'Hello Koa 2!'
  })
})

router.get('/string', async (ctx, next) => {
  ctx.body = 'koa2 string'
})

router.get('/json', async (ctx, next) => {
  let username = ctx.cookies.get("username")
  ctx.body = {
    title: 'koa2 json',
    username: username
  }
})

router.get('/testA', async (ctx) => {
  const a = await new Promise((resolve, reject) => {
    global.console.log('start' + new Date().getTime());
    setTimeout(() => {
      global.console.log('a' + new Date().getTime());
      resolve('abc');
    }, 1000)
  })
  ctx.body = {
    a,
  }
})

var User = require("../dbs/model/user.js");

router.get('/addUser', async (ctx) => {
  const user = new User({
    username: 'Tracy McGrady', //用户账号 
    userpwd: 'abcd', //密码
    userage: 37, //年龄 
    logindate: new Date() //最近登录时间 
  });
  let code = -1;
  try {
    code = 1
    user.save()
  } catch (error) {
    code = -1;
  }
  ctx.body = {
    code
  }
})

router.get('/getUser', async (ctx, next) => {
  let username = await User.findOne({"username" : "Tracy McGrady"})
  ctx.body = {
    username
  }
})

router.get('/updateUser', async (ctx, next) => {
  let username = await User.where({"username" : "Tracy McGrady"}).update({"userage" : 50})
  ctx.body = {
    username
  }
})

router.get('/removeUser', async (ctx, next) => {
  let username = await User.where({"username" : "Tracy McGrady"}).remove()
  ctx.body = {
    username
  }
})



module.exports = router
